package com.tutu.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tutu.cmn.listener.DictListener;
import com.tutu.cmn.mapper.DictMapper;
import com.tutu.cmn.service.DictService;
import com.tutu.model.cmn.Dict;
import com.tutu.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Program: yygh_parent
 * @Description:
 * @Author: JK.TuTu
 * @Create: 2022-09-18 18:00
 **/
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    /**
     * excel文件导出&&模板下载
     *
     * @param response
     * @param flag
     */
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void exportData(HttpServletResponse response, int flag) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //若为导出按钮  则查询所有数据进行写入
            if (flag == 1) {
                List<DictEeVo> dictEeVoList = dictMapper.selectList(null).stream().map((item) -> {
                    DictEeVo dictEeVo = new DictEeVo();
                    //将对象dict对象拷贝到DictEeVO
                    BeanUtils.copyProperties(item, dictEeVo);
                    return dictEeVo;
                }).collect(Collectors.toList());
                EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictEeVoList);
            } else {
                EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(new ArrayList());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * excel文件导入
     *
     * @param file
     */
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
